const pathToReg = require('../path-to-reg');
function Layer (path, handle) {
    this.path = path;
    this.handler = handle;
    this.reg = new RegExp(pathToReg(this.path, this.keys = []));// 为layer存放key
}

Layer.prototype.match = function (pathname) {
    if (pathname === this.path) {
        return true;
    }
    // 处理动态参数
    if (this.path.includes(':') && pathname.match(this.reg)) {
        let match = pathname.match(this.reg).slice(1);
        if (match) {
            this.params = {};
            this.keys.forEach((item, index) => {
                this.params[item.name] = match[index];
            })
            return true;
        }
    }

    // 中间件要use要处理
    // use的路由可以放宽匹配
    // use("/use")   能匹配  /use/a/b
    if (!this.route) {
        if(this.path === '/') {
            return true;
        }
        return pathname.startsWith(this.path + '/');
    }
    //都没匹配到，返回false
    return false;
}

Layer.prototype.handle_request = function (req, res, out) {
    // 如果是use的话，那么就直接执行这个函数，就不会找到route.dispatch
    this.handler(req, res, out);
}
Layer.prototype.handle_err = function (err, req, res, out) {
    // 是use,但是可能不是错误处理中间件，是四个参数才满足
    if (this.handler.length === 4) {
       console.log("aa");
        return this.handler(err, req, res, out);
    }
    out(err);
}
module.exports = Layer;